import {
  Button,
  message,
  Modal,
  notification,
  Space,
  TypographyText,
  Upload
} from 'ant-design-vue'
import moment from 'moment'
import { defineComponent, nextTick, onMounted, PropType, ref } from 'vue'
import { useRouter } from 'vue-router'
import * as xlsx from 'xlsx'

import { riverApi } from '@/apis'
import { LabelItem } from '@/apis/commonMenyTypes'
import { importOrders } from '@/apis/riverTypes'
import { type ProTableProps, type ProTableRef, ProTable } from '@/components'
import { TABLE_FORMAT, TABLE_ITEM_RENDER, TABLE_RENDERER } from '@/constants'
import { useDialog } from '@/hooks'
import { bus, download, downloadLink, optionsToMap } from '@/utils'
import { readFile } from '@/utils'
import { handlePrice } from '@/utils/bsshow'

import { forceOptions } from '../../financeManage/constants'

export default defineComponent({
  name: 'JdgGoodsManage',
  props: {
    peoples: {
      type: Array as PropType<Array<importOrders>>,
      required: true
    }
  },
  emits: ['dataCallback'],
  setup(props, { emit }) {
    const newRowNum = ref([] as any[])
    const showSetPriceDlg = ref(false)
    const optionGoodsItemCur = ref({} as any)
    const syncLoading = ref(false)
    const peopleList = ref(props.peoples as any[])
    const showSortDialog = ref(false)
    const dialogLoading = ref(false)
    const { showConfirm } = useDialog()
    const upDownStatusOptions = [
      { label: '全部', value: 0 },
      { label: '正向订单', value: 1 },
      { label: '逆向订单', value: 2 }
    ]
    const tableRef = ref({} as ProTableRef)
    const tableConfig = ref({
      fixedHeight: true,
      options: {
        border: true,
        align: 'center',
        toolbarConfig: {
          slots: {
            buttons: 'batchButtons'
          }
        },
        formConfig: {
          items: [
            {
              title: '商品名称',
              field: 'goodsName',
              itemRender: {
                name: TABLE_ITEM_RENDER.AInput,
                props: {
                  placeholder: '请输入',
                  allowClear: true
                }
              }
            },
            {
              title: '下单人ID',
              field: 'purchaserId',
              itemRender: {
                name: TABLE_ITEM_RENDER.AInput,
                props: {
                  placeholder: '请输入',
                  allowClear: true
                }
                // options: upDownStatusOptions
              }
            },
            {
              title: '线下订单唯一ID',
              field: 'offlineOrderSn',
              itemRender: {
                name: TABLE_ITEM_RENDER.AInput,
                props: {
                  placeholder: '请输入',
                  allowClear: true
                }
                // options: goodsTypeOptions
              }
            },
            {
              title: '销售公司名称',
              field: 'salesCompanyName',
              itemRender: {
                name: TABLE_ITEM_RENDER.AInput,
                props: {
                  placeholder: '请输入',
                  allowClear: true
                }
                // options: goodsTypeOptions
              }
            },
            {
              title: '订单下单时间',
              field: 'timeRange',
              itemRender: {
                name: TABLE_ITEM_RENDER.FormItemDate,
                props: {
                  type: 'range',
                  placeholder: ['开始时间', '结束时间'],
                  valueFormat: 'x',
                  showTime: {
                    defaultValue: [
                      moment('00:00:00', 'HH:mm:ss'),
                      moment('23:59:59', 'HH:mm:ss')
                    ]
                  },
                  keys: ['orderTimeBegin', 'orderTimeEnd']
                }
              }
            },
            // {
            //   title: '订单类型',
            //   field: 'orderType',
            //   itemRender: {
            //     name: TABLE_ITEM_RENDER.ASelect,
            //     props: {
            //       placeholder: '全部',
            //       allowClear: true
            //     },
            //     options: upDownStatusOptions
            //   }
            // },
            {
              title: '是否结算',
              field: 'isSettlement',
              itemRender: {
                name: TABLE_ITEM_RENDER.ASelect,
                props: {
                  placeholder: '全部',
                  allowClear: true
                },
                options: forceOptions
              }
            },
            {
              itemRender: {
                name: TABLE_RENDERER.FormItemBtns
              }
            }
          ]
        },
        columnConfig: {
          minWidth: 100,
          resizable: true
        },
        checkboxConfig: {
          showHeader: true,
          range: true
        },
        columns: [
          {
            type: 'checkbox',
            width: 50
          },
          {
            title: '线下订单唯一ID',
            field: 'offlineOrderSn'
          },
          {
            title: '是否已结算',
            slots: {
              default: 'isSettlement'
            }
          },
          {
            title: '反馈人员',
            field: 'feedbackStaffName',
            width: 200
          },
          {
            title: '下单人ID',
            field: 'purchaserId'
          },
          {
            title: '商品名称',
            field: 'goodsName',
            width: 250
          },
          {
            title: '商品个数',
            field: 'goodsNumber'
          },
          {
            title: '商品单价',
            field: 'goodsPrice'
          },
          {
            title: '收款金额',
            field: 'amountReceivedPrice'
          },
          {
            title: '产品备注',
            field: 'productRemarks',
            width: 120
          },
          {
            title: '销售公司名称',
            field: 'salesCompanyName'
            // formatter: ({ cellValue }) => {
            //   return optionsToMap(upDownStatusOptions)[cellValue]
            // }
          },
          {
            title: '销售公司wid',
            field: 'wid'
          },
          {
            title: '商品归属公司收益',
            field: 'goodsBelongToCompanyIncome'
          },
          {
            title: '订单下单时间',
            field: 'orderTime',
            width: 150,
            formatter: [TABLE_FORMAT.Date, 'yyyy-MM-dd HH:mm:ss']
          },
          {
            title: '订单类型',
            field: 'orderType'
          },
          {
            title: '逆行订单原订单',
            field: 'retrogradeOriginalOrder',
            width: 200
          },
          {
            title: '操作人',
            field: 'operator'
          },
          {
            title: '操作时间',
            field: 'operatingTime',
            width: 210,
            formatter: [TABLE_FORMAT.Date, 'yyyy-MM-dd HH:mm:ss']
          },
          {
            title: '备注',
            field: 'remark'
          },
          {
            title: '操作',
            fixed: 'right',
            slots: {
              default: 'operation'
            },
            width: 100
          }
        ],
        pagerConfig: {
          pageSize: 15
        },
        proxyConfig: {
          seq: true,
          form: true,
          props: {
            result: 'dataList',
            total: 'page.totalCount'
          },
          ajax: {
            query: async ({ page, form }) => {
              const data = await riverApi.queryOfflineOrder({
                pageParameter: {
                  pageSize: page.pageSize,
                  currentPage: page.currentPage
                },
                ...form
              })
              return data
            }
          }
        }
      }
    } as ProTableProps)

    onMounted(() => {
      bus.on('refreshJdgGoodsList', () => {
        nextTick(() => {
          tableRef.value.refresh()
        })
      })
    })
    //获取选中的项
    function getSelectedItems() {
      return tableRef.value.table?.getCheckboxRecords()
    }
    //批量删除
    function handleBatchDelete() {
      const selected = tableRef.value.table
        .getCheckboxRecords()
        .map(v => v.idImportOfflineOrder)
      console.log(selected)
      if (selected.length === 0) {
        return message.warn('请选择至少1条记录')
      }

      showConfirm({
        content: '确认批量删除？',
        onOk: async () => {
          tableRef.value.refresh(async () => {
            await riverApi.batchDelete({
              batchDelImportOfflineOrderIdList: selected
            })
            notification.success({
              message: '批量删除成功',
              duration: 1.5
            })
          })
        }
      })
    }
    const router = useRouter()
    //逐条删除
    function handleDelete(item) {
      showConfirm({
        content: '确认删除？',
        onOk: async () => {
          await tableRef.value.refresh(async () => {
            await riverApi.DeleteOrder(item.idImportOfflineOrder)
            notification.success({
              message: '删除成功',
              duration: 1.5
            })
          })
        }
      })
    }

    //导入订单excel
    const failList = ref()
    async function importOrder(params) {
      try {
        const formData = new FormData()
        formData.append('file', params.file)
        peopleList.value = await riverApi.importOfflineOrder(formData)
        refresh()
        const newFail = peopleList.value.failList
        const rowFailNum = newFail.map(item => {
          return item.rowNum
        })
        newRowNum.value = rowFailNum.join(',')
        if (newRowNum.value) {
          message.error(
            `第${newRowNum.value}条导入失败，导入成功${peopleList.value.successRow}条`
          )
        } else if (peopleList.value?.successRow) {
          message.success(`导入成功，共${peopleList.value.successRow}条`)
        }
      } catch {}
    }
    //刷新回调
    async function refresh() {
      await tableRef.value.table.commitProxy('query')
    }

    function handleRefresh(data) {
      peopleList.value = data
    }

    return {
      tableRef,
      tableConfig,
      showSetPriceDlg,
      optionGoodsItemCur,
      syncLoading,
      showSortDialog,
      dialogLoading,
      peopleList,
      failList,
      importOrder,
      handleRefresh,
      handleBatchDelete,
      handleDelete,
      getSelectedItems
    }
  },
  render() {
    return (
      <div>
        <ProTable
          ref="tableRef"
          v-slots={{
            batchButtons: () => (
              <Space>
                <Button type="primary" onClick={this.handleBatchDelete}>
                  批量删除
                </Button>
                <Upload
                  accept=".xlsx,.xls"
                  name="file"
                  customRequest={this.importOrder}
                  showUploadList={false}
                >
                  <Button type="primary">导入订单</Button>
                </Upload>
                <span>点击下载线下导入订单模板</span>
                <Button type="link" size="small">
                  <a href="https://yswy-agent.yjdfytmall.com/xh/offlineOrderImportTemplate.xlsx">
                    《线下订单导入模板》
                  </a>
                </Button>

                <span>后，填写订单后上传即可。</span>
              </Space>
            ),
            salePrice: ({ row }) => {
              return <Space>{handlePrice(row.salePrice, row.saleGold)}</Space>
            },
            isSettlement: ({ row }) => {
              return (
                <Space>
                  {row.isSettlement == 0 ? (
                    <TypographyText type="danger">否</TypographyText>
                  ) : (
                    <TypographyText type="success">是</TypographyText>
                  )}
                </Space>
              )
            },
            operation: ({ row }) => (
              <Space>
                <Button
                  type="link"
                  size="small"
                  onClick={() => this.handleDelete(row)}
                >
                  {row.isSettlement == 0 ? '删除' : ''}
                </Button>
              </Space>
            )
          }}
          {...this.tableConfig}
        />
      </div>
    )
  }
})
